package com.y3k.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import com.y3k.model.User;
import com.y3k.service.ServiceException;
import com.y3k.utils.ConfigurationUtil;
import com.y3k.utils.ConnectionHelper;
import com.y3k.utils.DAOException;

public class UserDao {

	public static final Logger log = Logger.getLogger(UserDao.class);

	protected User resultSetToObject(ResultSet rs) throws Exception {
		User usuario = new User();
		usuario.setUsername(rs.getString("username"));
		usuario.setPassword(rs.getString("password"));
		usuario.setEmail(rs.getString("email"));

		ProfileDao profileDao = new ProfileDao();
		usuario.setProfiles(profileDao.findAllBy(usuario.getUsername()));

		return usuario;
	}

	public User findBy(String username, String password) throws ServiceException {
		User usuario = null;
		Connection conn = null;

		try {
			conn = ConnectionHelper.getConnection();
			

			String sql = ConfigurationUtil.CONFIGURATION.getUserQuery();
			if (sql.toUpperCase().contains("WHERE")) {
				sql = sql + " and username=? and password=?";
			} else {
				sql = sql + " where username=? and password=?";
			}

			log.info(sql);
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				usuario = resultSetToObject(rs);
			}

			conn.commit();
		} catch (Exception ex) {
			throw new DAOException(ex);
		}

		return usuario;
	}
}